package home

import (
	"fmt"
	"github.com/beego/beego/v2/core/validation"
	"github.com/dchest/captcha"
	"net/http"
	"quickstart/global/response"
	"quickstart/services"
	"quickstart/utils"
)

type AccountController struct {
	BaseController
}

/*
登陆
*/
func (ac *AccountController) Login() {
	if ac.Ctx.Input.IsPost() {
		username := ac.GetString("username")
		password := ac.GetString("password")
		valid := validation.Validation{}
		valid.Required(username, "name")
		valid.Required(password, "password")
		if valid.HasErrors() {
			for _, err := range valid.Errors {
				response.ErrorWithMessage(err.Message, ac.Ctx)
			}
		}
		var authservice services.AuthService
		if authservice.Login(username, password, ac.Ctx) {
			fmt.Println("登陆成功")
			ac.Redirect("/", http.StatusFound)
			//redirect, _ := ac.GetSession("redirect").(string)
			//fmt.Println(redirect)
			//response.SuccessWithMessageAndUrl("登录成功", redirect, ac.Ctx)
		} else {
			response.ErrorWithMessage("登录失败:"+authservice.GetError(), ac.Ctx)
		}
	}
	ac.TplName = "account/login.html"
}

/*
注册
*/
func (ac *AccountController) Register() {
	if ac.Ctx.Input.IsPost() {
		username := ac.GetString("username")
		password := ac.GetString("password")
		email := ac.GetString("email")
		mobile := ac.GetString("mobile")
		captcha1 := ac.GetString("captcha")
		captchaId := ac.GetString("captchaId")
		valid := validation.Validation{}
		valid.Required(username, "name")
		valid.Required(password, "password")
		valid.Required(email, "email")
		valid.Required(mobile, "mobile")
		if valid.HasErrors() {
			for _, err := range valid.Errors {
				response.ErrorWithMessage(err.Message, ac.Ctx)
			}
		}
		//校验验证码
		valid.Required(captcha1, "captcha").Message("请输入验证码.")
		if ok := captcha.VerifyString(captchaId, captcha1); !ok {
			response.ErrorWithMessage("验证码错误.", ac.Ctx)
		}

		var authservice services.AuthService
		if authservice.Register(username, password, ac.Ctx, mobile, email) {
			ac.Redirect("/", http.StatusFound)
			fmt.Println("注册成功")
		}
		fmt.Println("注册失败" + authservice.GetError())
	}
	ac.Data["captcha"] = utils.GetCaptcha()
	fmt.Println(ac.Data["captcha"])
	ac.TplName = "account/register.html"
}

/*
退出登陆
*/
func (ac *AccountController) Logout() {
	if ac.Auth.Logout(ac.Ctx) {
		fmt.Println("退出成功")
		ac.Redirect("/", http.StatusFound)
	}
	response.Error(ac.Ctx)
}

// RefreshCaptcha 刷新验证码
func (ac *AccountController) RefreshCaptcha() {
	captchaID := ac.GetString("captchaId")
	res := map[string]interface{}{
		"isNew": false,
	}
	if captchaID == "" {
		res["msg"] = "参数错误."
	}
	isReload := captcha.Reload(captchaID)
	if isReload {
		res["captchaId"] = captchaID
	} else {
		res["isNew"] = true
		res["captcha"] = utils.GetCaptcha()
	}
	ac.Data["json"] = res
	ac.ServeJSON()
}
